/**
* All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
*
* PmProjectChangeService
* 项目基本信息变更申请
*
* 修改纪录
* 2020-06-10 版本：1.0 liwanpeng 创建。
* @version 版本：1.0
* @author 作者：liwanpeng
* 创建日期：2020-06-10
*/
package com.topscomm.pm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.pm.PmSystemConst;
import com.topscomm.pm.pojo.PmProjectEntity;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.tap.common.ParameterCache;
import java.util.List;
import java.util.Map;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;

import com.topscomm.pm.service.IPmProjectChangeService;
import com.topscomm.pm.service.impl.auto.PmProjectChangeServiceAuto;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.pm.pojo.PmProjectChangeEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

@Service(value = "pmProjectChangeService")
@Scope(value = "singleton")
public class PmProjectChangeService extends PmProjectChangeServiceAuto implements IPmProjectChangeService {
	/**
	 * @author: liwanpeng
	 * @date: 2020-06-10
	 * @param entity
	 * @throws
	 * @description:单号生成
	 * @modify:
	 */
	@Override
	protected void beforeInsert(BasicEntity entity){
		super.beforeInsert(entity);
		if (entity.getId() <= 0) {// 赋值Id和单号
			long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
			entity.setId(arrayId[0]);
			String docNo = String.valueOf(arrayId[0]);
			docNo = docNo.substring(0, 6) + docNo.substring(9);
			entity.setValue(PmProjectChangeEntity.FieldDocno, docNo);
		}
	}

	@Transactional(rollbackFor = Exception.class)
	public Boolean judgeExistsErpItemCode(String ownerorgcode2,String projectcode)
		throws Exception {
		SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
		requestFactory.setConnectTimeout(2000);// 设置超时
		requestFactory.setReadTimeout(100000);// 读取超时时间
		RestTemplate restTemplate = new RestTemplate(requestFactory);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		String token = ParameterCache.getValue(PmSystemConst.DataServiceToken);
		String templateid = ParameterCache.getValue(PmSystemConst.GetIfExistsErpItemCode);
		headers.set("token", token);
		JSONObject map = new JSONObject();
		map.put("templateid", templateid);
		try{
			String url = ParameterCache.getValue(PmSystemConst.DataServiceUrl);
			JSONObject params = new JSONObject();
			params.put("orgCode",ownerorgcode2);
			params.put("itemCode",projectcode);
			map.put("paramsMap",params);
			HttpEntity<JSONObject> request = new HttpEntity<>(map, headers);
			ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, request, JSONObject.class);
		    if(response.getBody().getBooleanValue("success")==true){
				List<Map<String, Object>> maps = (List<Map<String, Object>>) response.getBody()
					.getJSONObject("result").get("dataList");
				return maps.size()>0;
			}else{
		    	throw new Exception(response.getBody().getString("message"));
			}
		}catch (Exception ex){
			throw new Exception(ex.getMessage());
		}
	}


	/**
	 * @author: wudaliang
	 * @date: 2021-09-28
	 * @param: pmProjectEntity
	 * @param: pmProjectChangeEntity
	 * @description: 立项变更审批通过后，对应组织下如果不存在项目号则新建
	 * @return: void
	 * @modify:
	 */
	@Transactional(rollbackFor = Exception.class)
	public void pmChangeAddErpItem(PmProjectEntity pmProjectEntity,PmProjectChangeEntity pmProjectChangeEntity)
		throws Exception {
		if (pmProjectEntity != null) {
			String orgcode = pmProjectChangeEntity.getOwnerorgcode2();
			JSONObject map = new JSONObject();
			map.put("system", "pm");
			map.put("ident", pmProjectChangeEntity.getTableName()+"_"+pmProjectChangeEntity.getId());
			map.put("orgcode", orgcode);
			map.put("inventoryuomgroup", 5);//库存主单位计量单位组
			map.put("inventoryUOMCode", "PCS");//库存主单位
			map.put("inventoryseconduomcode", "PCS");//库存主单位
			map.put("code",pmProjectEntity.getCode() );
			map.put("name",pmProjectEntity.getName());
			map.put("itemformattribute", "10");//制造件
			map.put("bomenable", false);//是否可BOM
			map.put("inventoryenable",false);//是否可库存交易
			map.put("mrpenable", false);//是否可MRP
			map.put("outsideoperationenable", false);//是否可委外
			map.put("purchaseenable", false);//是否可采购
			map.put("salesenable", true);//可销售

			if("D1".equals(orgcode))//股份
			{
				map.put("StockCategoryCode", "K22");//库存分类 运维服务
				map.put("assetcategorycode", "07");//财务分类 07安装服务 06技术服务 05资产
				map.put("productioncategorycode", "A03");//生产分类 其他
			}else if("D22".equals(orgcode))//电力工程
			{
				map.put("StockCategoryCode", "K22");//库存分类 运维服务
				map.put("assetcategorycode", "22C03");//财务分类 07安装服务 06技术服务 05资产
				map.put("productioncategorycode", "A03");//生产分类 其他
			} else if("D22F01".equals(orgcode))//四川
			{
				map.put("StockCategoryCode", "K22");//库存分类 运维服务
				map.put("productioncategorycode", "A03");//生产分类 其他
			} else if("D22F02".equals(orgcode))//重庆
			{
				map.put("StockCategoryCode", "K22");//库存分类 运维服务
				map.put("productioncategorycode", "A03");//生产分类 其他
			}  else if("D22F03".equals(orgcode))//河北
			{
				map.put("StockCategoryCode", "K22");//库存分类 运维服务
				map.put("productioncategorycode", "A03");//生产分类 其他
			}  else if("D22F04".equals(orgcode))//湖南
			{
				map.put("StockCategoryCode", "K22");//库存分类 运维服务
				map.put("productioncategorycode", "A03");//生产分类 其他
			}  else if("D26".equals(orgcode))//科远
			{
				map.put("StockCategoryCode", "K22");//库存分类 运维服务
				map.put("productioncategorycode", "A03");//生产分类 其他
			}

			SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
			requestFactory.setConnectTimeout(2000);// 设置超时
			requestFactory.setReadTimeout(10000);//读取超时时间
			RestTemplate restTemplate = new RestTemplate(requestFactory);
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
			String token = ParameterCache.getValue("ERPServiceUrl_Token");
			headers.set("token", token);
			//map.put("templateid", "20061200000001");
			HttpEntity<JSONObject> request = new HttpEntity<>(map, headers);

			try {
				String url = ParameterCache.getValue("ERPUrl_ItemCreate");
				ResponseEntity<JSONObject> response = restTemplate
					.postForEntity(url, request, JSONObject.class);
				//如果失败
				if(response.getBody().getBooleanValue("success")==false)
				{
					String errorCode = response.getBody().getString("errorCode");
					if(!"409".equals(errorCode))//不是做单重复的
					{
						throw new Exception(response.getBody().getString("message"));
					}
				}
			}
			catch(Exception e)
			{
				throw new Exception(e.getMessage());
			}
		}
	}
}
